package com.wxit.algorithm.leetcode;

/**
 * 判断回文链表
 */
public class E09LeetCode234 {

    /**
     * 1.找中间的节点
     * 2.中间点后半个链表进行反转
     * 3.反转后链表与原来链表进行逐一比较
     */
    public ListNode middleNode(ListNode head) {
        ListNode p1 = head;
        ListNode p2 = head;
        while (p2 != null && p2.next != null) {
            p1 = p1.next;
            p2 = p2.next.next;
        }
        return p1;
    }

    public ListNode reverseList(ListNode o1) {
        if (o1 == null || o1.next == null) {
            return o1;
        }
        ListNode n1 = null;
        while (o1 != null) {
            ListNode o2 = o1.next;
            o1.next = n1;
            n1 = o1;
            o1 = o2;
        }
        return n1;
    }

    public boolean isPalindrome(ListNode head) {
        ListNode middled = middleNode(head);
        ListNode newHead = reverseList(middled);
        while (newHead != null) {
            if (newHead.val != head.val) {
                return false;
            }
            newHead = newHead.next;
            head = head.next;
        }
        return true;
    }

    public static void main(String[] args) {
        System.out.println(new E09LeetCode234().isPalindrome(ListNode.of(1, 2, 3, 1)));
        System.out.println(new E09LeetCode234().isPalindrome(ListNode.of(1, 2, 3, 2, 1)));
    }
}
